package cn.luke.basic.controller;


import cn.luke.basic.debounces.Debounce;
import cn.luke.basic.entity.DtoTemplate;
import cn.luke.basic.entity.DtoUserTemplate;
import cn.luke.basic.entity.req.ReqTemplateCount;
import cn.luke.basic.enums.EnumCountType;
import cn.luke.basic.log_api.LogApi;
import cn.luke.basic.rs.ResponseResult;
import cn.luke.basic.services.ServiceTemplate;
import cn.luke.basic.services.ServiceUserTemplate;
import cn.luke.basic.utils.MyAssert;
import cn.luke.basic.utils.UtilsEnum;
import com.baomidou.mybatisplus.core.metadata.IPage;
import jakarta.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Map;


/**
 * 用户关联模板
 * pathName
 * //
 */

@RestController
@ResponseResult
@RequestMapping("/userTemplate")
public class ControllerUserTemplate implements MyAssert {
    @Resource
    private ServiceUserTemplate serviceUserTemplate;

    @Resource
    private ServiceTemplate serviceTemplate;


    /**
     * 用户关联模板-保存
     */
    @Debounce
    @LogApi("用户关联模板-保存")
    @PostMapping("/userRelevanceTemplate")
//    @SaCheckPermission("userTemplate.save")
    public void save(@RequestBody DtoUserTemplate userTemplate) {
        intIsNull(userTemplate.getUserId(), "用户id");
        intIsNull(userTemplate.getTemplateId(), "模板id");
        intIsNull(userTemplate.getRelevanceUserId(), "关联用户id");
        serviceUserTemplate.save(userTemplate);
    }



    /**
     * 根据用户id查询模板集合
     */
    @Debounce
    @PostMapping("/findPageByUser")
    public IPage<DtoTemplate> get(@RequestBody Map<String, Object> params) {
        pageIsNull(params);
        return serviceUserTemplate.findPageByUser(params);
    }

    /**
     * 根据模板和用户id查询模板详情
     */
    @Debounce
    @GetMapping("/findByUserId")
    public DtoTemplate findByUserId(@RequestParam("userId") Integer userId,
                                    @RequestParam("templateId") Integer templateId,
                                    @RequestParam("id") Integer id) {
        return serviceUserTemplate.findById(userId, templateId, id);
    }

    /**
     * 根据用户id查询访问量集合
     */
    @Debounce
    @GetMapping("/findSumCountByUserId")
    public DtoUserTemplate findByUserId(@RequestParam("userId") Integer userId) {
        return serviceUserTemplate.findByUserId(userId);
    }

    /**
     * 更新相关数据量
     */
    @PostMapping("/addCount")
    @Transactional
    public void addPageViewCount(@RequestBody ReqTemplateCount reqTemplateCount) {
        UtilsEnum.existsInEnum(EnumCountType.class, reqTemplateCount.getType());
        serviceUserTemplate.addCount(reqTemplateCount);
        serviceTemplate.addCount(reqTemplateCount.getTemplateId(), reqTemplateCount.getType());
    }

}
